package com.example.pda.view;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.FrameLayout;

import com.example.pda.adapter.StockListAdapter;
import com.example.pda.common.CommonCallback;
import com.example.pda.common.Utils;
import com.example.pda.data.model.HwList;
import com.example.pda.data.model.StockList;

import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class SpinnerPopupView<T> implements TextWatcher {

    private String searchText = "";      //改变后的文字
    private WaitThread waitThread;  //等待线程
    private int curTime;            //当前延时时间


    private final Handler mHandler;

    private final ItemInputLayout mLayout;
    private final RecyclerView mRecyclerView;
    private final List<T> mList;
    private StockListAdapter<T> adapter;
    private final CommonCallback<T> mCommonCallback;


    public SpinnerPopupView(NestedScrollView scrollView, ItemInputLayout layout, RecyclerView recyclerView,
                            List<T> list, String curId, CommonCallback<T> commonCallback) {
        mLayout = layout;
        mRecyclerView = recyclerView;
        mList = list;
        mCommonCallback = commonCallback;
        LinearLayoutCompat parent = (LinearLayoutCompat) mRecyclerView.getParent();
        if (parent != null) {
            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) parent.getLayoutParams();
            layoutParams.topMargin = layout.getHeight() * (layout.getIndex() + 1) - scrollView.getScrollY();
            parent.setLayoutParams(layoutParams);
        }
        layout.getBinding().evValue.addTextChangedListener(this);
        layout.getBinding().evValue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                LinearLayoutCompat parent = (LinearLayoutCompat) mRecyclerView.getParent();
                if (parent != null) {
                    parent.setVisibility(hasFocus ? View.VISIBLE : View.GONE);
                }
            }
        });
        //异步处理
        mHandler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                //更新回调接口
                if (0 == msg.what) {
                    waitThread = null;
                    //匹配结果回调
                    List<T> searchList = new ArrayList<>();
                    if (TextUtils.isEmpty(searchText)) {
                        if (mCommonCallback != null) {
                            mCommonCallback.onResult(null);
                        }
                        return;
                    }
                    if (!Utils.isEmpty(mList)) {
                        for (T o : mList) {
                            if (o instanceof HwList && ((HwList) o).getHwname().contains(searchText)) {
                                searchList.add(o);
                            } else if (o instanceof StockList && ((StockList) o).getStockname().contains(searchText)) {
                                searchList.add(o);
                            }
                        }
                        initRecycler(searchList);
                    }
                }
            }
        };
        if (parent != null) {
            parent.setVisibility(View.VISIBLE);
        }
        initRecycler(list);
        if (!Utils.isEmpty(mList) && !TextUtils.isEmpty(curId)) {
            for (T o : mList) {
                if (o instanceof HwList && ((HwList) o).getHwcode().contains(curId)) {
                    adapter.setCurItem(o);
                    return;
                } else if (o instanceof StockList && ((StockList) o).getStockcode().contains(curId)) {
                    adapter.setCurItem(o);
                    return;
                }
            }
        }
    }

    private void initRecycler(List<T> data) {
        if (adapter == null) {
            mRecyclerView.setLayoutManager(new LinearLayoutManager(mLayout.getContext()));
            adapter = new StockListAdapter<>();
            adapter.setListener(new CommonCallback<T>() {
                @Override
                public void onResult(T item, Object... objects) {
                    if (item instanceof HwList) {
                        searchText = ((HwList) item).getHwname();
                    }
                    if (item instanceof StockList) {
                        searchText = ((StockList) item).getStockname();
                    }
                    adapter.setCurItem(item);
                    mLayout.getBinding().evValue.removeTextChangedListener(SpinnerPopupView.this);
                    LinearLayoutCompat parent = (LinearLayoutCompat) mRecyclerView.getParent();
                    if (parent != null) {
                        parent.setVisibility(View.GONE);
                    }
                    if (mCommonCallback != null) {
                        mCommonCallback.onResult(item, objects);
                    }
                }
            });
            mRecyclerView.setAdapter(adapter);
        }
        adapter.setData(data);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        //搜索框的文字发生变化就重置等待时间
        if (!searchText.equals(s.toString())) {
            searchText = s.toString();
            mHandler.sendEmptyMessageAtTime(0, 100);
        }
    }

    /**
     * 延时搜索的线程
     */
    private class WaitThread extends Thread {
        @Override
        public void run() {
            //等待延时
            //延时搜索时间，默认200ms
            int waitTime = 200;
            //当前延时时间
            for (curTime = 0; curTime < waitTime; curTime += 100) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            mHandler.sendEmptyMessage(0);
        }
    }


}
